//
//  HWSearchViewController.m
//  24Home
//
//  Created by shw on 14-7-17.
//  Copyright (c) 2014年 DongHao. All rights reserved.
//

#import "HWSearchViewController.h"
#import "HttpRequestManager.h"
#import "SVProgressHUD.h"
//#import "PageInfo.h"
//#import "Organization.h"
#import "UIColor+FlatUI.h"
#import "HTDefine.h"
#import "CommityListViewController.h"
#import "CommodityListCell.h"
#import "merchantListCell.h"
#import "CityBrandListCell.h"
#import "KInterFace.h"
#import "GetSupplierQuery.h"
#import "BrandDetail.h"
#import "RepairAndHomeViewController.h"
#import "WaresDetailViewController.h"
#import "BranddetailsViewController.h"
#import "SVPullToRefresh.h"

#define SavePathMerchant         ([NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MerchantObject.plist"])
#define SavePathCommodity         ([NSHomeDirectory() stringByAppendingPathComponent:@"Documents/CommodityObject.plist"])
#define SavePathBrand         ([NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BrandObject.plist"])
#define SavePathInformation         ([NSHomeDirectory() stringByAppendingPathComponent:@"Documents/InformationObject.plist"])

NSString *const commodityListCellID = @"CommodityListCellID";
NSString *const merchantListCellID = @"MerchantListCellID";
NSString *const cityBrandListCellID = @"CityBrandListCellID";
@interface HWSearchViewController ()<CommidityListCellDelegate>

@property (nonatomic, weak) IBOutlet UIButton *merchantButton;
@property (nonatomic, weak) IBOutlet UIButton *commodityButton;
@property (nonatomic, weak) IBOutlet UIButton *brandButton;
@property (nonatomic, weak) IBOutlet UIButton *informationButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewRightSide;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewLeftSide;


@property (nonatomic, assign) KSearchStatues searchStatues;
@property (nonatomic, assign) KSearchResultStatus searchStatusResult;
@property (nonatomic, strong) NSMutableArray *localArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) IBOutlet UIView *footerView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@property (nonatomic, assign) int page;
@property (weak, nonatomic) IBOutlet UILabel *searchLabel;

@end

@implementation HWSearchViewController

#pragma mark - View Life Cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self.searchBar becomeFirstResponder];
    [self initData];
    self.page = 1;
    self.searchStatues = KSearchStatuesMerchant;
    self.searchStatusResult = KSearchResultStatusReady;
    self.merchantButton.selected = YES;
    
    CALayer *layer = [self.searchBar layer];
    [layer setMasksToBounds:YES];
    [layer setCornerRadius:0.0];
    
    //设置边框线的宽
    self.searchLabel.hidden = YES;
    //
    [layer setBorderWidth:1];
    //设置边框线的颜色
    
    [layer setBorderColor:[[UIColor clearColor] CGColor]]; //想要的颜色
//    [[self.searchBar.subviews objectAtIndex:0] layer].borderColor = [UIColor lightGrayColor].CGColor;
//    [[self.searchBar.subviews objectAtIndex:0] layer].borderWidth = 0.5;

//    self.searchBar.layer.borderWidth = 0.5;
//    self.searchBar.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    self.searchBar.layer.cornerRadius = 1.0;
    self.searchBar.clipsToBounds = YES;
    [self.tableView registerNib:[CommodityListCell nib] forCellReuseIdentifier:commodityListCellID];
    [self.tableView registerNib:[merchantListCell nib] forCellReuseIdentifier:merchantListCellID];
    [self.tableView registerNib:[CityBrandListCell nib] forCellReuseIdentifier:cityBrandListCellID];
    __weak typeof(self)weakSelf = self;
    [self.tableView addPullToRefreshWithActionHandler:^{
        weakSelf.page = 1;
        [weakSelf webRequest_GetOrganizaitonsWithSearchText:weakSelf.searchBar.text WithMore:NO];
    }];
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetOrganizaitonsWithSearchText:weakSelf.searchBar.text WithMore:YES];
    }];
    [self.tableView triggerPullToRefresh];
//    self.tableView.showsInfiniteScrolling = NO;

}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [super viewWillAppear:animated];
    [self.searchBar becomeFirstResponder];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.searchDisplayController.searchBar becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    switch (self.searchStatues) {
        case KSearchStatuesMerchant:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathMerchant];
        }
            break;
        case KSearchStatuesCommodity:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathCommodity];
        }
            break;
        case KSearchStatuesBrand:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathBrand];
        }
            break;
        case KSearchStatuesInformation:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathInformation];
        }
            break;
            
        default:
            break;
    }

}

#pragma mark - Setups
- (void)initData
{
    self.dataArray = [NSMutableArray array];
    self.localArray = [NSMutableArray array];
    switch (self.searchStatues) {
        case KSearchStatuesMerchant:{
            self.localArray = [self loadFromFileUnarchiver:SavePathMerchant];
        }
            break;
        case KSearchStatuesCommodity:{
            self.localArray = [self loadFromFileUnarchiver:SavePathCommodity];

        }
            break;
        case KSearchStatuesBrand:{
            self.localArray = [self loadFromFileUnarchiver:SavePathBrand];
        }
            break;
        case KSearchStatuesInformation:{
            self.localArray = [self loadFromFileUnarchiver:SavePathInformation];
        }
            break;
            
        default:
            break;
    }
    [self.tableView reloadData];
}

#pragma mark - Actions
-(IBAction)merchantButton_Touch:(id)sender
{
    self.searchLabel.hidden = YES;
    self.page = 1;
    self.tableViewLeftSide.constant = 0.0f;
    self.tableViewRightSide.constant = 0.0f;
    self.searchStatusResult = KSearchResultStatusReady;
    self.searchBar.placeholder = @"请输入商户名称";
    self.searchStatues = KSearchStatuesMerchant;
    self.merchantButton.selected = YES;
    self.commodityButton.selected = NO;
    self.brandButton.selected = NO;
    self.informationButton.selected = NO;
    [self initData];
}

-(IBAction)commodityButton_Touch:(id)sender
{
    self.searchLabel.hidden = YES;
    self.page = 1;
    self.tableViewLeftSide.constant = 0.0f;
    self.tableViewRightSide.constant = 0.0f;
    self.searchStatusResult = KSearchResultStatusReady;
    self.searchBar.placeholder = @"请输入商品名称";
    self.searchStatues = KSearchStatuesCommodity;
    self.merchantButton.selected = NO;
    self.commodityButton.selected = YES;
    self.brandButton.selected = NO;
    self.informationButton.selected = NO;
    [self initData];

}

-(IBAction)brandButton_Touch:(id)sender
{
    self.searchLabel.hidden = YES;
    self.page = 1;
    self.tableViewLeftSide.constant = 0.0f;
    self.tableViewRightSide.constant = 0.0f;
    self.searchStatusResult = KSearchResultStatusReady;
    self.searchBar.placeholder = @"请输入品牌名称";
    self.searchStatues = KSearchStatuesBrand;
    self.merchantButton.selected = NO;
    self.commodityButton.selected = NO;
    self.brandButton.selected = YES;
    self.informationButton.selected = NO;
    [self initData];
}

-(IBAction)informationButton_Touch:(id)sender
{
    self.searchLabel.hidden = YES;
    self.page = 1;
    self.tableViewLeftSide.constant = 0.0f;
    self.tableViewRightSide.constant = 0.0f;
    self.searchStatusResult = KSearchResultStatusReady;
    self.searchBar.placeholder = @"请输入资讯内容";
    self.searchStatues = KSearchStatuesInformation;
    self.merchantButton.selected = NO;
    self.commodityButton.selected = NO;
    self.brandButton.selected = NO;
    self.informationButton.selected = YES;
    [self initData];
}

-(IBAction)backButton_Touch:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(IBAction)searchButton_Touch:(id)sender
{
    if (self.searchBar.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入搜索内容"];
        return;
    }
    [self.localArray addObject:self.searchBar.text];
    switch (self.searchStatues) {
        case KSearchStatuesMerchant:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathMerchant];
        }
            break;
        case KSearchStatuesCommodity:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathCommodity];
        }
            break;
        case KSearchStatuesBrand:{
            self.tableViewLeftSide.constant = 5.0f;
            self.tableViewRightSide.constant = 5.0f;
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathBrand];
        }
            break;
        case KSearchStatuesInformation:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathInformation];
        }
            break;
            
        default:
            break;
    }
    [self webRequest_GetOrganizaitonsWithSearchText:self.searchBar.text WithMore:NO];
//    goodsListViewController *goodListVC = [[goodsListViewController alloc]initWithtypeOfShowSearchHeaderView:YES];
//    [self.navigationController pushViewController:goodListVC animated:YES];
}

#pragma mark - CommidityListCellDelegate
-(void)addShopCartWithCommidityID:(NSString *)commodityID
{
    
}

#pragma mark - WebRequest
- (void)webRequest_GetOrganizaitonsWithSearchText:(NSString *)searchText WithMore:(BOOL)isMore
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if(self.searchStatues == KSearchStatuesCommodity){
        NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@/city/%@/page/%i",KInterface_GetGoodsQuery,@"name",searchText,[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",isMore?self.page:0];
    [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            self.searchStatusResult = KSearchResultStatusFinish;
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
            }
            [self.tableView reloadData];
            if (self.arrayRequest.count == 0) {
                self.searchLabel.hidden = NO;
            }else{
                self.searchLabel.hidden = YES;
            }
        }
        if (isMore) {
            [self.tableView.infiniteScrollingView stopAnimating];
        }else{
            [self.tableView.pullToRefreshView stopAnimating];
        }
    }];
    }else if (self.searchStatues == KSearchStatuesMerchant){
        NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@/city/%@/page/%i",KInterface_GetSupplierQuery,@"name",searchText,[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",isMore?self.page:0];
        [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                DLog(@"%@",response);
                self.searchStatusResult = KSearchResultStatusFinish;
                if (isMore) {
                    [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                    self.page = self.page + 1;
                }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
                }
                [self.tableView reloadData];
                if (self.arrayRequest.count == 0) {
                    self.searchLabel.hidden = NO;
                }else{
                    self.searchLabel.hidden = YES;
                }
            }
            if (isMore) {
                [self.tableView.infiniteScrollingView stopAnimating];
            }else{
                [self.tableView.pullToRefreshView stopAnimating];
            }
        }];
    }else if (self.searchStatues == KSearchStatuesBrand){
//        self.tableView.separatorStyle = uitableviewcell;
        NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@/page/%i",KInterface_GetBrandList,@"name",searchText,isMore?self.page:0];
        [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                DLog(@"%@",response);
                self.searchStatusResult = KSearchResultStatusFinish;
                if (isMore) {
                    [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                    self.page = self.page + 1;
                }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
                }
                [self.tableView reloadData];
                if (self.arrayRequest.count == 0) {
                    self.searchLabel.hidden = NO;
                }else{
                    self.searchLabel.hidden = YES;
                }
            }
            if (isMore) {
                [self.tableView.infiniteScrollingView stopAnimating];
            }else{
                [self.tableView.pullToRefreshView stopAnimating];
            }
        }];
    }
}

#pragma mark - UITableView Delegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
        return 1;
    }else{
        if (self.searchStatues == KSearchStatuesBrand)
        {
            return self.arrayRequest.count;
        }else{
            return 1;
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
    UILabel * label = [[UILabel alloc] init] ;
    label.frame = CGRectMake(15, 5, 200, 20);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor colorFromHexCode:@"333333"];
//    label.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 220)] ;
    [sectionView setBackgroundColor:[UIColor colorFromHexCode:@"FFF3E2"]];
    [sectionView addSubview:label];
    
    UIImageView *imageOne = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 1)];
    [imageOne setImage:[UIImage imageNamed:@""]];
    [imageOne setBackgroundColor:[UIColor colorFromHexCode:@"ECECEC"]];
    
    UIImageView *imageTwo = [[UIImageView alloc]initWithFrame:CGRectMake(0, 29, tableView.bounds.size.width, 1)];
    [imageTwo setImage:[UIImage imageNamed:@""]];
    [imageTwo setBackgroundColor:[UIColor colorFromHexCode:@"ECECEC"]];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, 5, 20, 20)];
    [imageView setImage:[UIImage imageNamed:@"recom"]];
    [sectionView addSubview:imageView];
    [sectionView addSubview:imageOne];
    [sectionView addSubview:imageTwo];
    [label setFrame:CGRectMake(45, 5, 200, 20)];
    label.textColor = [UIColor colorFromHexCode:@"8E8E8E"];
    
    [sectionView setBackgroundColor:[UIColor colorFromHexCode:@"EEEEEE"]];
    
    label.text = @"搜索历史";
    label.font = [UIFont systemFontOfSize:14];
    return sectionView;
    }else if (self.searchStatues == KSearchStatuesBrand)
    {
        UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 220)] ;
        [sectionView setBackgroundColor:[UIColor colorFromHexCode:@"F4F3ED"]];
        return sectionView;
    }
    else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
        return 30;
    }else{
        if (self.searchStatues == KSearchStatuesBrand)
        {
            return 10;
        }else{
            return 0;
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//    return @"搜索历史";
    return nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
      if (self.localArray.count == 0) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }else{
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    return self.localArray.count;
    }else{
        if (self.searchStatues == KSearchStatuesBrand)
        {
            return 1;
        }else{
            return self.arrayRequest.count;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [self.localArray objectAtIndex:indexPath.row];

    return cell;
    }else{
        if (self.searchStatues == KSearchStatuesMerchant) {
            merchantListCell *merchantListCell = [tableView dequeueReusableCellWithIdentifier:merchantListCellID];
            GetSupplierQuery *merchant = [GetSupplierQuery objectFromDictionary:self.arrayRequest[indexPath.row]];
            [merchantListCell configWithMerchant:merchant];
            return merchantListCell;
        }else if (self.searchStatues == KSearchStatuesCommodity){
        CommodityListCell *commodityListCell = [tableView dequeueReusableCellWithIdentifier:commodityListCellID];
            GetGoodsQuery *commodity = [GetGoodsQuery objectFromDictionary:self.arrayRequest[indexPath.row]];
            commodityListCell.contentLabel.text = commodity.name;
            [commodityListCell configWithCommidity:commodity];
        return commodityListCell;
        }else if (self.searchStatues == KSearchStatuesBrand)
        {
            CityBrandListCell *cityBrandListCell = [tableView dequeueReusableCellWithIdentifier:cityBrandListCellID];
            BrandDetail *brand = [BrandDetail objectFromDictionary:self.arrayRequest[indexPath.section]];
            [cityBrandListCell configWithBrandDetail:brand];
            return cityBrandListCell;
        }else{
            static NSString *CellIdentifier = @"asasxsxdcsd";
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            }
            cell.backgroundColor = [UIColor whiteColor];
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.searchBar.text = self.localArray[indexPath.row];
    }else{
        DLog(@"进入详情");
        [self.tableView reloadData];
        if (self.searchStatues == KSearchStatuesMerchant) {
            GetSupplierQuery *merchant = [GetSupplierQuery objectFromDictionary:self.arrayRequest[indexPath.row]];
            RepairAndHomeViewController *repairAndHomeViewController = [[RepairAndHomeViewController alloc]initWithMerchantID:merchant.objectId];
            [self.navigationController pushViewController:repairAndHomeViewController animated:YES];
        }else if (self.searchStatues == KSearchStatuesCommodity) {
            GetGoodsQuery *commodity = [GetGoodsQuery objectFromDictionary:self.arrayRequest[indexPath.row]];
            WaresDetailViewController *waresDetailViewController = [[WaresDetailViewController alloc]initWithCommodityID:commodity.objectId];
            [self.navigationController pushViewController:waresDetailViewController animated:YES];
        }else if (self.searchStatues == KSearchStatuesBrand){
            BrandDetail *brandDetail = [BrandDetail objectFromDictionary:self.arrayRequest[indexPath.section]];
            BranddetailsViewController *branddetailsViewController = [[BranddetailsViewController alloc]initWithBrandID:brandDetail.objectId];
            [self.navigationController pushViewController:branddetailsViewController animated:YES];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
        if (self.localArray.count > 0)
            return 44;
        else
            return 0;
    }else{
        if (self.searchStatues == KSearchStatuesBrand)
        {
            if(section == self.arrayRequest.count)
            {
                return 10;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
        return 44;
    }else{
        if (self.searchStatues == KSearchStatuesMerchant) {
            return [merchantListCell heightOfTableCell];
        }else if (self.searchStatues == KSearchStatuesCommodity){
            return [CommodityListCell heightOfTableCell];
        }else
        {
            return [CityBrandListCell heightOfTableCell];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (self.searchStatusResult == KSearchResultStatusReady) {
        if (self.localArray.count > 0)
            return self.footerView;
        else
            return nil;
    }else{
        return nil;
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (IBAction)clearHistoryBtnClick:(id)sender {
    [self.localArray removeAllObjects];
    switch (self.searchStatues) {
        case KSearchStatuesMerchant:{
            [self saveToFileArchiver:self.localArray path:SavePathMerchant];
        }
            break;
        case KSearchStatuesCommodity:{
            [self saveToFileArchiver:self.localArray path:SavePathCommodity];
            
        }
            break;
        case KSearchStatuesBrand:{
            [self saveToFileArchiver:self.localArray path:SavePathBrand];
        }
            break;
        case KSearchStatuesInformation:{
            [self saveToFileArchiver:self.localArray path:SavePathInformation];
        }
            break;
            
        default:
            break;
    }
//    if (self.localArray.count == 0) {
//        self.tableView.hidden = YES;
//    }else
//    {
//        self.tableView.hidden = NO;
//    }
    [self.tableView reloadData];
}

#pragma mark - Search Bar Delegate Method
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;   // called
{
    
    
//    NSLog(@"------%@",self.searchBar.text);
    //    [_famousPersons  addObject:self.searchBar.text];
    [self.dataArray removeAllObjects];
//    [self  getdata:searchBar.text];
    
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
//    CATransition *animation = [CATransition animation];
//    animation.duration = 0.3;
//    animation.timingFunction = UIViewAnimationCurveEaseInOut;
////    animation.type = @"pageUnCurl";
//    animation.type = kCATransitionPush;
//    animation.subtype = kCATransitionFromLeft;
//    [self.view.layer addAnimation:animation forKey:nil];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.localArray addObject:searchBar.text];
    switch (self.searchStatues) {
        case KSearchStatuesMerchant:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathMerchant];
        }
            break;
        case KSearchStatuesCommodity:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathCommodity];
        }
            break;
        case KSearchStatuesBrand:{
            self.tableViewLeftSide.constant = 5.0f;
            self.tableViewRightSide.constant = 5.0f;
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathBrand];
        }
            break;
        case KSearchStatuesInformation:{
            NSMutableArray *array = [self arrayWithMemberIsOnly:self.localArray];
            [self saveToFileArchiver:array path:SavePathInformation];
        }
            break;
            
        default:
            break;
    }
    [self webRequest_GetOrganizaitonsWithSearchText:self.searchBar.text WithMore:NO];
//    CommityListViewController *goodListVC = [[CommityListViewController alloc]initWithtypeOfShowSearchHeaderView:YES];
//    CommityListViewController *goodlistv
//    [self.navigationController pushViewController:goodListVC animated:YES];
//    [self webRequest_GetOrganizaitonsWithSearchText:searchBar.text];
}

#pragma mark - 历史记录相关
- (NSMutableArray *)arrayWithMemberIsOnly:(NSMutableArray *)array
{
    NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < [array count]; i++) {
        if ([categoryArray containsObject:[array objectAtIndex:i]] == NO){
            [categoryArray addObject:[array objectAtIndex:i]];
        }
    }
    return categoryArray;
}

- (BOOL)saveToFileArchiver:(id)obj path:(NSString *)path
{
    [NSKeyedArchiver archiveRootObject:obj toFile:path];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:obj];
    return [data writeToFile:path atomically:YES];
}

- (NSMutableArray *)loadFromFileUnarchiver:(NSString *)path {
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSMutableArray *obj = [NSMutableArray array];
    obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];

    return obj;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
